package com.example.bluetooth;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 13430 on 2018/9/29.
 */
public class BLEPositioning {
    private Context currContext;
    private Handler handler;
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    public static final int mode = 0;
    private String imei = "";
    // 存储蓝牙扫描结果，key - name_address, value - List<IBeaconRecord>
    private Map<String, IBeaconRecord> mapBltScanResult;
    private boolean isLog = true;

    public BLEPositioning(Context ctx) {
        super();
        this.currContext = ctx;
        initParam();       //判断sdk是否大于17 ，否则不可用

    }

    /**
     * 初始化
     */
    private void initParam() {
        handler = new Handler();
        mapBltScanResult = new HashMap<String, IBeaconRecord>();
        // 设备SDK版本大于17（Build.VERSION_CODES.JELLY_BEAN_MR1）才支持BLE 4.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            bluetoothManager = (BluetoothManager) this.currContext
                    .getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();
        } else {
            tip(currContext, "当前系统版本不支持蓝牙BLE 4.0.");
//            System.out.println("当前系统版本不支持蓝牙BLE 4.0.");
        }
    }

    public void tip(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }


    public static SampleScanCallBack sampleScanCallBack;

    /**
     * 开始扫描蓝牙设备
     */
    public void startScan() {
        try {
            if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
                //指定需要识别到的蓝牙设备
                List<ScanFilter> scanFilterList = new ArrayList<>();

                ScanFilter.Builder builder2 = new ScanFilter.Builder();
//                builder2.setDeviceName("QZS_BC");//你要扫描的设备的名称，如果使用lightble这个app来模拟蓝牙可以直接设置name，这个只是filter的一种，你可以指定uuid,这个只是指定设备名
                ScanFilter scanFilter2 = builder2.build();

//        scanFilterList.add(scanFilter);
                scanFilterList.add(scanFilter2);

                //指定蓝牙的方式，这里设置的ScanSettings.SCAN_MODE_LOW_POWER是比较节电的扫描方式，而且在效率方面没有很大的影响，而且相当省电
                ScanSettings.Builder settingBuilder = new ScanSettings.Builder();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    settingBuilder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    settingBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
                }
                settingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    settingBuilder.setLegacy(true);
                }
                ScanSettings settings = settingBuilder.build();
                sampleScanCallBack = new SampleScanCallBack();

                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilterList, settings, sampleScanCallBack);
                mBluetoothAdapter.startLeScan(bltScanCallback);
//                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback); // 开始扫描
            }
        } catch (Exception ex) {
            Log.e("startScan error", ex.getMessage());
        }
    }

    private class SampleScanCallBack extends ScanCallback {
        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            System.out.println("扫描结果" + result.getDevice().getName() + ":" + result.getDevice() + ":" + result.getRssi());
        }
    }


    public void stopScan() {
        mBluetoothAdapter.getBluetoothLeScanner().stopScan(sampleScanCallBack);
        mBluetoothAdapter.stopLeScan(bltScanCallback);
    }

    /**
     * 请求定位服务，由你们完成，
     * 如果指纹数据在本地，定位算法就在当前App里完成
     */


    private BluetoothAdapter.LeScanCallback bltScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {

            System.out.println("扫描结果" + device.getName() + ":" + device.getAddress() + ":" + rssi);

        }
    };

}
